package com.peas.platform.module.icims.expenditure.kpis.domain.impl;

import cn.hutool.core.util.StrUtil;
import com.peas.platform.framework.mybatisplus.domain.BaseDomainImpl;
import com.peas.platform.framework.mybatisplus.repository.BaseRepository;
import com.peas.platform.module.icims.base.sys.service.SequenceService;
import com.peas.platform.module.icims.expenditure.kpis.adapter.repository.ExpenditureKpiRepository;
import com.peas.platform.module.icims.expenditure.kpis.adapter.repository.po.ExpenditureKpiPo;
import com.peas.platform.module.icims.expenditure.kpis.domain.ExpenditureKpiDomain;
import com.peas.platform.module.icims.expenditure.kpis.dto.ExpenditureKpiDto;
import com.peas.platform.module.icims.expenditure.kpis.dto.ExpenditureKpiItemDto;
import com.peas.platform.module.icims.expenditure.kpis.service.ExpenditureKpiItemService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

@Component
public class ExpenditureKpiDomainImpl extends BaseDomainImpl<ExpenditureKpiDto, ExpenditureKpiPo> implements ExpenditureKpiDomain {

    @Resource
    private ExpenditureKpiRepository expenditureKpiRepository;
    @Resource
    private SequenceService sequenceService;
    @Resource
    private ExpenditureKpiItemService expenditureKpiItemService;

    @Override
    public BaseRepository<ExpenditureKpiPo> getMapper() {
        return expenditureKpiRepository;
    }

    @Override
    public Class<? extends BaseRepository<ExpenditureKpiPo>> getRepositoryClass() {
        return ExpenditureKpiRepository.class;
    }

    @Transactional
    @Override
    public int save(ExpenditureKpiDto dto) {
        if (StrUtil.isBlank(dto.getKpiCode())) {
            String code = sequenceService.genSequence("expenditure", "ExpenditureKpiDto", "EKDD", 4, 1);
            dto.setKpiCode(code);
        }
        int result = super.save(dto);
        this.checkRepetition("kpiCode", dto.getKpiCode());
        return result;
    }

    @Transactional
    @Override
    public int updateById(ExpenditureKpiDto dto) {
        int result = super.updateById(dto);
        this.checkRepetition("kpiCode", dto.getKpiCode());
        return result;
    }

    @Transactional
    @Override
    public int removeById(Serializable id) {
        int result = super.removeById(id);
        List<ExpenditureKpiItemDto> list = expenditureKpiItemService.listByField("expenditureKpiId", id);
        expenditureKpiItemService.removeBatchByList(list);
        return result;
    }

}
